# -*- coding: utf-8 -*-
import sip
sip.setapi('QString', 2)
sip.setapi('QStringList', 2)
sip.setapi('QVariant', 2)

from PyQt4 import QtCore

#_______________________________________________________________________________
class PlaylistTreeController(QtCore.QObject):
    def __init__(self, server_ctrl, model, view):
        # TODO: creare un wrapper per python_mpd unicode->str, str->unicode
        QtCore.QObject.__init__(self)
        self.view = view
        self.model = model
        self.server_ctrl = server_ctrl
        #Signal
        self.server_ctrl.client_connected.connect(self.setup)
        self.server_ctrl.playlist_changed.connect(self.update_model)
        self.server_ctrl.player_song_changed.connect(self.update_state)
        self.server_ctrl.player_started.connect(self.update_state)
        self.server_ctrl.player_stopped.connect(self.update_state)
        self.server_ctrl.player_paused.connect(self.update_state)
#        self.server_ctrl.database_updated.connect(self.model.reload_data)
        self.view.playlist_cleared.connect(self.clear)
        self.view.songs_deleted.connect(self.delete_songs)
        self.view.song_doubleclicked.connect(self.play_doubleclicked_song)
        self.model.moved_songs.connect(self.move_songs)
        self.model.added_songs.connect(self.add_songs)
    
    def setup(self, connected):
        if connected:
            self.view.setEnabled(True)
            self.model.pl_version = self.server_ctrl.model.info_status["playlist"]
            songs = self.server_ctrl.client.playlistinfo()
            self.model.setup_data(songs)
    
    def update_model(self):
        # 4 possibilità:
        # 1 - pl svuotata
        pl_current_length = self.model.rowCount()
        if (pl_current_length != 0 and 
            self.server_ctrl.model.info_status["playlistlength"] == 0):
            self.model.clear()
            return
        # 2 - canzoni aggiunte
        if (pl_current_length < self.server_ctrl.model.info_status["playlistlength"]):
            ids_changed = self.server_ctrl.client.plchangesposid(self.model.pl_version)
            positions = [ids_changed[i]["cpos"] for i in xrange(len(ids_changed)) 
                         if ids_changed[i]["id"] not in self.model.idrow_map]
            positions.sort(key=int)
            songs_data = [self.server_ctrl.client.playlistinfo(position)[0] 
                          for position in positions]
            self.model.add_songs(songs_data) 
        # 3 - canzoni spostate
        elif (pl_current_length == self.server_ctrl.model.info_status["playlistlength"]):
            ids_changed = self.server_ctrl.client.plchangesposid(self.model.pl_version)
            ids_changed.sort(key=lambda x: int(x["cpos"]))
            self.model.move_songs(ids_changed)
        # 4 - canzoni cancellate
        else:
            ids_changed = self.server_ctrl.client.plchangesposid(self.model.pl_version)
            ids_changed.sort(key=lambda x: int(x["cpos"]))
            diff = pl_current_length - self.server_ctrl.model.info_status["playlistlength"]
            self.model.remove_songs(ids_changed, diff)
        self.model.pl_version = self.server_ctrl.model.info_status["playlist"]

    def update_state(self):
        id = self.server_ctrl.model.info_status.get("songid")
        state = self.server_ctrl.model.info_status["state"]
        self.model.update_item_state(id, state)

    def delete_songs(self, indexes):
        if not list:
            return
        ids = self.model.get_selected_songs(indexes)
        self.server_ctrl.client.command_list_ok_begin()
        for id in ids:
            self.server_ctrl.client.deleteid(id)                
        self.server_ctrl.client.command_list_end()
    
    def add_songs(self, songs, row):
        self.server_ctrl.client.command_list_ok_begin()
        for song in songs:
            self.server_ctrl.client.addid(song, row)
            row += 1
        self.server_ctrl.client.command_list_end()          
    
    def move_songs(self, movements):
        self.server_ctrl.client.command_list_ok_begin()
        for id, row in movements:
            self.server_ctrl.client.moveid(id, row)
        self.server_ctrl.client.command_list_end()
    
    def clear(self):
        self.server_ctrl.client.clear()
    
    def play_doubleclicked_song(self, id):
        self.server_ctrl.client.playid(id)